package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.AddFamilyMemberRequestDto;
import com.zzyl.nursing.dto.DeviceDataListDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.IWechatService;
import com.zzyl.nursing.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 *
 * @author syl
 * @date 2025-05-30
 */
@Service
@Slf4j
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper,FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember)?1:0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember)?1:0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id)?1:0;
    }

    @Autowired
    private IWechatService wechatService;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private TokenService tokenService;  //这是zzyl-framework模块中的
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public LoginVo login(UserLoginRequestDto dto) {
        String code = dto.getCode();
        String phoneCode = dto.getPhoneCode();

        // 调用微信接口返回openid
        String openid = wechatService.getOpenid(code);

        // 根据openid查询客户信息
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId, openid);
        FamilyMember familyMember = familyMemberMapper.selectOne(queryWrapper);

        String phone = wechatService.getPhone(phoneCode); //这里要注意获取手机号用的是phoneCode
        if(familyMember==null){
            familyMember = new FamilyMember();
            familyMember.setPhone(phone);
            //从DEFAULT_NICKNAME_PREFIX随机挑选一个 + 手机号的后四位 0-8
            familyMember.setName(DEFAULT_NICKNAME_PREFIX.get(new Random().nextInt(DEFAULT_NICKNAME_PREFIX.size()))+phone.substring(7));
            familyMember.setOpenId(openid);
            familyMemberMapper.insert(familyMember);
        }else{
            // 这个用户是否修改过手机号
            if (!StrUtil.equals(familyMember.getPhone(),phone)) {
                familyMember.setPhone(phone);
            }
            familyMemberMapper.updateById(familyMember);

        }
        // 根据用户ID和昵称生成Jwt的token
        Map<String, Object> map = new HashMap();
        map.put("id", familyMember.getId());
        map.put("nickName", familyMember.getName());
        String token = tokenService.createToken(map); //这里注意把tokenService.createToken改成public

        LoginVo  loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        return loginVo;
    }

    @Override
    public void addFamilyRelation(AddFamilyMemberRequestDto dto) {
        // 获取当前登录用户ID
        Long userId = UserThreadLocal.get();
        // 根据身份证号和姓名查询老人信息
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, dto.getIdCard());
        queryWrapper.eq(Elder::getName, dto.getName());
        Elder elder = elderMapper.selectOne(queryWrapper);

        // 创建家庭成员关联记录
        FamilyMemberElder familyMemberElder = new FamilyMemberElder();

        familyMemberElder.setMemberId(userId);
        familyMemberElder.setElderId(elder.getId());
        familyMemberElder.setRemark(dto.getRemark());
        familyMemberElder.setCreateTime(new Date());
        familyMemberMapper.add(familyMemberElder);

    }

    @Override
    public List<FamilyMemberVo> getFamilyElderList() {
        return List.of();
    }

    @Override
    public List<DeviceDataVo> queryServiceProperties(String iotId) {
        Object object = redisTemplate.boundHashOps(CacheConstants.IOT_DEVICE_LAST_DATA).get(iotId);
        List<DeviceData> deviceDataList = JSONUtil.toList(object.toString(), DeviceData.class);
        ArrayList<DeviceDataVo> voList = new ArrayList<>();
        for (DeviceData deviceData : deviceDataList) {
            DeviceDataVo deviceDataVo = new DeviceDataVo();
            deviceDataVo.setFunctionId(deviceData.getFunctionId());
            deviceDataVo.setEventTime(deviceData.getAlarmTime());
            deviceDataVo.setValue(deviceData.getDataValue());
            voList.add(deviceDataVo);
        }
        return voList;
    }

    @Override
    public List<FamilyMemberElderVo> listByPage() {
        ArrayList<FamilyMemberElderVo> voList = new ArrayList<>();
        Long userId = UserThreadLocal.get();
        List<FamilyMemberElder> familyMemberElders =
                familyMemberElderMapper.selectList(Wrappers.<FamilyMemberElder>lambdaQuery().eq(FamilyMemberElder::getMemberId, userId));
        if (familyMemberElders == null || familyMemberElders.isEmpty()) {
            return voList;
        }
        for (FamilyMemberElder familyMemberElder : familyMemberElders) {
            FamilyMemberElderVo familyMemberElderVo = new FamilyMemberElderVo();

            Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getId, familyMemberElder.getElderId()));
            if(elder == null) {
                log.info("绑定的老人为空");
                continue;
            }
            String roomTypeName = bedMapper.getRoomType(elder.getBedId());
            Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getBindingLocation, elder.getId()));
            if(device != null) {
                familyMemberElderVo.setIotId(device.getIotId());
                familyMemberElderVo.setDeviceName(device.getDeviceName());
                familyMemberElderVo.setProductKey(device.getProductKey());
            }
            familyMemberElderVo.setMid(userId.toString());
            familyMemberElderVo.setMremark(familyMemberElder.getRemark());
            familyMemberElderVo.setElderId(familyMemberElder.getElderId().toString());
            familyMemberElderVo.setName(elder.getName());
            familyMemberElderVo.setImage(elder.getImage());
            familyMemberElderVo.setBedNumber(elder.getBedNumber());
            familyMemberElderVo.setTypeName(roomTypeName);
            voList.add(familyMemberElderVo);
        }

        return voList;
    }
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Override
    public List<DeviceDataByDayVo> queryDeviceDataListByDay(DeviceDataListDto dto) {
        LocalDateTime startTime = LocalDateTimeUtil.of(dto.getStartTime());
        LocalDateTime endTime = LocalDateTimeUtil.of(dto.getEndTime());

        List<DeviceDataByDayVo> byDayList;
        byDayList = deviceDataMapper.queryDeviceDataListByDay(dto.getIotId(), dto.getFunctionId(), startTime.toString(), endTime.toString());
        if (byDayList == null || byDayList.size() == 0) {
            return byDayList;
        }
        //查出的dateTime由String转为Int
        HashMap<Integer, Double> deviceDataByDayMap = new HashMap<>();
        for (DeviceDataByDayVo deviceDataByDayVo : byDayList) {
            Integer hour = Integer.valueOf(deviceDataByDayVo.getDateTime());
            deviceDataByDayMap.put(hour, deviceDataByDayVo.getDataValue());
        }
        List<DeviceDataByDayVo> byDayListFormat = new ArrayList<>();
        for (int i = 0; i < 24; i++) {
            DeviceDataByDayVo deviceDataByDayVo = new DeviceDataByDayVo();
            if (deviceDataByDayMap.containsKey(i)) {
                deviceDataByDayVo.setDataValue(deviceDataByDayMap.get(i));
            } else {
                deviceDataByDayVo.setDataValue(0D);
            }
            if (i < 10) {
                deviceDataByDayVo.setDateTime("0" + i + ":00");
            } else {
                deviceDataByDayVo.setDateTime(i + ":00");
            }
            byDayListFormat.add(deviceDataByDayVo);
        }

        return byDayListFormat;
    }

    @Override
    public List<DeviceDataByWeekVo> queryDeviceDataListByWeek(DeviceDataListDto dto) {
        LocalDateTime startTime = LocalDateTimeUtil.of(dto.getStartTime());
        LocalDateTime endTime = LocalDateTimeUtil.of(dto.getEndTime());

        List<DeviceDataByWeekVo> byWeekList;
        byWeekList = deviceDataMapper.queryDeviceDataListByWeek(dto.getIotId(), dto.getFunctionId(), startTime.toString(), endTime.toString());
        if (byWeekList == null || byWeekList.size() == 0) {
            return byWeekList;
        }

        Map<String, Integer> map = new HashMap<>();
        for (DeviceDataByWeekVo byWeekVo : byWeekList) {
            map.put(byWeekVo.getDateTime(), byWeekVo.getDataValue());
        }

        List<DeviceDataByWeekVo> byWeekListFormat = new ArrayList<>();
        LocalDate now = LocalDate.now();
        for (int i = -6; i <= 0; i++) {
            LocalDate oldLocalDate = now.plusDays(i);
            int monthValue = oldLocalDate.getMonthValue();
            int dayOfMonth = oldLocalDate.getDayOfMonth();
            String monthStr = monthValue < 10 ? "0" + monthValue : "" + monthValue;
            String dayStr = dayOfMonth < 10 ? "0" + dayOfMonth : "" + dayOfMonth;
            String dateTime = monthStr + "." + dayStr;

            DeviceDataByWeekVo byWeekVo = new DeviceDataByWeekVo();
            byWeekVo.setDateTime(dateTime);
            if (map.containsKey(dateTime)) {
                byWeekVo.setDataValue(map.get(dateTime));
            } else {
                byWeekVo.setDataValue(0);
            }
            byWeekListFormat.add(byWeekVo);
        }


        return byWeekListFormat;
    }

    @Override
    public void deleteById(Integer id) {
        familyMemberElderMapper.delete(Wrappers.<FamilyMemberElder>lambdaQuery().eq(FamilyMemberElder::getMemberId, id));
    }

    @Autowired
        private FamilyMemberElderMapper familyMemberElderMapper;
    @Autowired
        private BedMapper bedMapper;
        @Autowired
        private DeviceMapper deviceMapper;


    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of("生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

}
